package cn.kgc.message.service.impl;

import cn.hutool.json.JSONUtil;
import cn.kgc.message.utils.ResponseResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.message.entiy.Message;
import cn.kgc.message.service.MessageService;
import cn.kgc.message.mapper.MessageMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author mengshun
* @description 针对表【message】的数据库操作Service实现
* @createDate 2024-01-10 13:46:21
*/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService{


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 1.留言提交   redis   mysql
    @Override
    public ResponseResult addMessage(Message message) {

        message.setCreateTime(new Date());
        // 1. 保存留言redis
        String jsonMessage = JSONUtil.toJsonStr(message);
        stringRedisTemplate.opsForHash().put(message.getDeviceId(),"permanent",jsonMessage);

        // 2. 保存留言到mysql
        baseMapper.insert(message);

        // 3. 删除ip对应的 暂存留言  temp
        Boolean hasTemp = stringRedisTemplate.opsForHash().hasKey(message.getDeviceId(), "temp");
        if (hasTemp){
            stringRedisTemplate.opsForHash().delete(message.getDeviceId(),"temp");
        }

        return ResponseResult.success().message("留言添加成功");
    }

    @Override
    public ResponseResult tempMessage(Message message) {

        message.setCreateTime(new Date());
        //  1.暂存留言存入redis
        stringRedisTemplate.opsForHash().put(message.getDeviceId(),"temp",JSONUtil.toJsonStr(message));

        // 2. 删除 ip 对应的持久化信息
        Boolean hasPermanent = stringRedisTemplate.opsForHash().hasKey(message.getDeviceId(), "permanent");
        if (hasPermanent){
            stringRedisTemplate.opsForHash().delete(message.getDeviceId(),"permanent");
        }
        return ResponseResult.success().message("留言暂存成功");
    }

    @Override
    public ResponseResult getMessageByDeviceId(String ip) {

        Object message = null;
        if (stringRedisTemplate.opsForHash().hasKey(ip,"temp")){
            message =  JSONUtil.parse(stringRedisTemplate.opsForHash().get(ip,"temp"));
        }else {
            message =  JSONUtil.parse(stringRedisTemplate.opsForHash().get(ip,"permanent"));
        }

        return ResponseResult.success().data(message);
    }
}




